package com.jingdianjichi.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.jingdianjichi.auth.application.convert.AuthUserDTOConverter;
import com.jingdianjichi.auth.domain.entity.AuthUserBO;
import com.jingdianjichi.auth.entity.AuthUserDTO;
import com.jingdianjichi.auth.entity.Result;
import com.jingdianjichi.auth.service.AuthUserDomainService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private AuthUserDomainService authUserDomainService;

//    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
//    @RequestMapping("doLogin")
//    public String doLogin(String username, String password) {
//        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
//        if("zhang".equals(username) && "123456".equals(password)) {
//            StpUtil.login(10001);
//            return "登录成功";
//        }
//        return "登录失败";
//    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("/isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

    // 登录接口
    @RequestMapping("/doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String validCode) {
        if (log.isInfoEnabled()) {
            log.info("UserController.doLogin.validCode:{}", JSON.toJSONString(validCode));
        }

        try {
            Preconditions.checkArgument(!StringUtils.isBlank(validCode), "验证码不能为空");
            SaTokenInfo tokenInfo = authUserDomainService.doLogin(validCode);
            return Result.ok(tokenInfo);
        } catch (Exception e) {
            log.error("UserController.doLogin.error:{}", e.getMessage(), e);
            return Result.fail("用户登录失败");
        }
    }
    //        // 第1步，先登录上
//        if ("zhang".equals(username) && "123456".equals(password)) {
//            StpUtil.login("鸡翅");
//            // 第2步，获取 Token  相关参数
//            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
//            // 第3步，返回给前端
//            return SaResult.data(tokenInfo);
//        }


    /**
     * 注册
     *
     * @param authUserDTO
     * @return
     */
    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {

        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.register.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()), "邮件地址不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "用户名不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()), "密码不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOtoBo(authUserDTO);
            Boolean bean = authUserDomainService.register(authUserBO);
            return Result.ok(bean);
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage(), e);
            return Result.fail("注册用户失败");
        }

    }

    /**
     * 修改用户信息
     *
     * @param authUserDTO
     * @return
     */
    @PostMapping("/update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {

        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }

            Preconditions.checkNotNull(authUserDTO.getUserName(), "用户昵称不能为空");


            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOtoBo(authUserDTO);
            Boolean bean = authUserDomainService.update(authUserBO);
            return Result.ok(bean);
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return Result.fail("修改用户信息失败");
        }

    }

    /**
     * 删除用户
     *
     * @param authUserDTO
     * @return
     */
    @PostMapping("/delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO) {

        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.delete.dto:{}", JSON.toJSONString(authUserDTO));
            }

            Preconditions.checkNotNull(authUserDTO.getId(), "用户id不能为空");
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOtoBo(authUserDTO);
            Boolean bean = authUserDomainService.delete(authUserBO);
            return Result.ok(bean);
        } catch (Exception e) {
            log.error("UserController.delete.error:{}", e.getMessage(), e);
            return Result.fail("删除用户信息失败");
        }

    }

    /**
     * 用户启用禁用
     *
     * @param authUserDTO
     * @return
     */
    @PostMapping("/changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDTO) {

        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.changeStatus.dto:{}", JSON.toJSONString(authUserDTO));
            }

            Preconditions.checkNotNull(authUserDTO.getId(), "用户id不能为空");
            Preconditions.checkNotNull(authUserDTO.getStatus(), "用户状态不能为空");
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOtoBo(authUserDTO);
            Boolean bean = authUserDomainService.changeStatus(authUserBO);
            return Result.ok(bean);
        } catch (Exception e) {
            log.error("UserController.changeStatus.error:{}", e.getMessage(), e);
            return Result.fail("删除用户信息失败");
        }

    }

    /**
     * 获取用户信息
     *
     * @param authUserDTO
     * @return
     */
    @PostMapping("/getUserInfo")
    public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDTO) {

        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.getUserInfo.dto:{}", JSON.toJSONString(authUserDTO));
            }

            Preconditions.checkNotNull(authUserDTO.getUserName(), "用户名称（openId）不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOtoBo(authUserDTO);
            AuthUserBO authUserBOResult = authUserDomainService.getUserInfo(authUserBO);
            AuthUserDTO authUserDTOResult = AuthUserDTOConverter.INSTANCE.convertBotoDTO(authUserBOResult);
            return Result.ok(authUserDTOResult);
        } catch (Exception e) {
            log.error("UserController.getUserInfo.error:{}", e.getMessage(), e);
            return Result.fail("获取用户信息失败");
        }

    }

    /**
     * 用户退出登录
     *
     * @param userName
     * @return
     */
    @RequestMapping("/logOut")
    public Result logout(@RequestParam String userName) {

        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.logout.userName:{}", JSON.toJSONString(userName));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(userName), "用户名称（openId）不能为空");
            StpUtil.logout(userName);
            return Result.ok();
        } catch (Exception e) {
            log.error("UserController.logout.error:{}", e.getMessage(), e);
            return Result.fail("用户退出登录失败");
        }

    }
}
